<?php

namespace app\common\model;

use think\db\BaseQuery;
use utils\Ip;

class ClientModel extends BaseModel
{
    //protected $autoWriteTimestamp = true;

    public $name = 'client';

    /**
     * 获取公司的所有客服
     * @param $admin_id
     */
    static function getKefuIds($admin_id){
        $ids = self::findAll(['role'=>1,"admin_id"=>$admin_id],'id');
        return array_column($ids,'id');
    }



    static function getInfo($id){
        $where = [
            'id'=>$id,
        ];
        $field = "id,role,admin_id,depart_id,staff_id,name,mobile,uid,extend,headimg";
        $info = self::findOne($where,$field);
        $info['uuid'] = $info['id'];
        return $info;
    }

//对客户信息 进行处理 统一数据格式
    static function handleUserInfo($info,$online=1){
        //防止重复处理
        if(isset($info['isHandle'])){
            return $info;
        }
        $new_info = [
            'id'=>$info['id'],
            'uuid'=>'1_'.$info['id'],
            'uid'=>$info['uid'],
            'nickname'=>$info['name'],
            'role'=>2,
            'headimg'=>$info['headimg'],
            'mobile'=>$info['mobile'],
            'isHandle'=>1,
            'online'=>$online,//在线
        ];

        $new_info['append'] = array_diff_key($info,$new_info);
        return $new_info;
    }

//创建新客户  客户存在 则返回基本的客户信息
    static function createInfo($param,$admin_id){
        $where = [
            'admin_id'=>$admin_id,
            'uid'=>$param['userid'],
        ];
        $field="id,admin_id,depart_id,staff_id,name,mobile,uid,extend,headimg";
        $info = self::findOne($where,$field);
        $data = [
            'admin_id'=>$admin_id,
//            'depart_id'=>$param['depart_id'],
//            'staff_id'=>$param['staff_id'],
            'name'=>$param['username'],
            'mobile'=>$param['mobile'],
            'uid'=>$param['userid'],
            'extend'=>urldecode($param['extend']),
            'online'=>time(),
            'headimg'=>$param['headimg']?:'',
        ];
        $data = array_filter($data);
//        dump($data);exit;
        if($info){
            //已经存在  更新数据
            $data = array_merge($info,$data);
            $data['depart_id'] = $param['depart_id']?:0;
            $data['staff_id'] = $param['staff_id']?:0;
            $data['update_time'] = $data['online'];
//            dump($data);exit;
            self::updates(['id'=>$info['id']],$data);
            $info_id = $info['id'];
        }else{
            //生成一个随机的名字
            if(empty($data['name'])) $data['name'] = self::getRandomName();
            if(empty($data['headimg'])) $data['headimg'] = self::getRandomHeadimg();

            //新增记录
            $info_id = self::saveData($data);
            $info = self::findOne(['id'=>$info_id],$field);

        }
        $data['uid'] = $info_id;
        $data['os'] =  getOs();
        $data['header'] =  getBroswer();
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['source'] = $_SERVER['HTTP_REFERER'];//来源站点
        $data['ip'] = request()->ip();//来访ip
        $data['ip_text'] = implode(' ', Ip::find($data['ip']));//ip所在地
//        dump($data);exit;
        unset($data['id']);
        //写入访问日志
        ClientLogModel::saveData($data);
        $info_simple = [
            'id'=>$info['id'],
            'uuid'=>$info['id'],
            'admin_id'=>$info['admin_id'],
            'nickname'=>$info['name'],
            'headimg'=>$info['headimg'],
            'uid'=>$info['uid'],
            'role'=>2,
        ];
//        dump($info_simple);exit;

        //将客户信息返回
        return $info_simple;
    }

//创建客服账户
    static function createInfo2($StaffInfo){
        $admin_id = $StaffInfo['admin_id'];
        $where = [
            'admin_id'=>$admin_id,
            'uid'=>$StaffInfo['id'],
        ];
        $field="id,admin_id,depart_id,staff_id,name,mobile,uid,extend,headimg";
        $info = self::findOne($where,$field);
//        dump($info);exit;
        if($info){
            //存在 账户 更新账户信息
            $data = [
                'admin_id'=>$admin_id,
                'depart_id'=>$StaffInfo['depart_id'],
                'staff_id'=>$StaffInfo['id'],
                'name'=>$StaffInfo['name'],
                'mobile'=>$StaffInfo['mobile'],
                'uid'=>$StaffInfo['id'],
                'headimg'=>$StaffInfo['head'],
                'online'=>time(),
            ];
            //存在 更新客服信息
            self::updates(['id'=>$info['id']],$data);
            $data['id'] = $info['id'];
        }else{
            //创建账户
            $data = [
                'role'=>1,//客服
                'admin_id'=>$admin_id,
                'depart_id'=>$StaffInfo['depart_id'],
                'staff_id'=>$StaffInfo['id'],
                'name'=>$StaffInfo['name'],
                'mobile'=>$StaffInfo['mobile'],
                'uid'=>$StaffInfo['id'],
                'headimg'=>$StaffInfo['headimg'],
                'extend'=>'',
                'online'=>time(),
            ];
            $data['id'] = self::saveData($data);
        }
        $info_simple = [
            'id'=>$StaffInfo['id'],
            'uuid'=>$data['id'],
            'admin_id'=>$data['admin_id'],
            'nickname'=>$data['name'],
            'headimg'=>$data['headimg'],
            'uid'=>$data['uid'],
            'role'=>1,
        ];
        //将客户信息返回
        return $info_simple;
    }

/**
     * 获取用户的随机名称
     */
    static function getRandomName(){
        return substr(md5(uniqid()),0,8);
    }



    static function getRandomHeadimg(){
        $number = mt_rand(0,31);
        return "/static/head/{$number}.jpg";
    }

        //数据查询
    function getList($param){
        $order = $param['order']?:'id desc';
        $model = $this->order($order);
        $this->getListWhere($model,$param);
        $list = $model->paginate($param['limit']);
        return $list;
    }

    //获取导出数据
    function getExport($param,$fileName='',$type='xlsx'){
        $fileName = $fileName?:'数据表格';
        $fileName.='-'.date('YmdHis');
        //获取数据
        $order = $param['order']?:'id desc';
        $model = $this->order($order);
        $this->getListWhere($model,$param);
        $list = $model->select();
        if(empty($list)){
            return [];
        }
        foreach ($list as $k=>$v){
            if(is_numeric($v->create_time))$list[$k]['create_time'] = $v->create_time_text;
            if(is_numeric($v->update_time))$list[$k]['update_time'] = $v->update_time_text;

        }
        $list = $list->toArray();
        //得到表头
        $top = array_intersect_key(self::$fieldsList,$list[0]);
        //移除部分表头
        $top = array_diff_key($top,array_flip([]));
        //移除多余字段
        $list_new = [];
        foreach ($list as $k=>$v){
            $list_new[] = array_intersect_key($v,$top);
        }
        $list = $list_new;
        return [
            'fileName'=>$fileName,
            'top'=>$top,
            'data'=>$list,
            'type'=>$type,
        ];
    }

    /**
     * 设置列表查询条件
     * @param BaseQuery $model
     * @param array $param
     * @return array
     */
    function getListWhere($model,$param=[]){
        if(empty($param)){
            return [];
        }
        $where = [];
            
        if($param['id']){
            $where['id'] = $param['id'];
        }
    
        if($param['role']){
            $where['role'] = $param['role'];
        }
    
        if($param['depart_id']){
            $where['depart_id'] = $param['depart_id'];
        }
    
        if($param['staff_id']){
            $where['staff_id'] = $param['staff_id'];
        }
    
        if($param['name']){
            $where['name'] = $param['name'];
        }
    
        if($param['mobile']){
            $where['mobile'] = $param['mobile'];
        }
    
        if($param['password']){
            $where['password'] = $param['password'];
        }
    
        if($param['uid']){
            $where['uid'] = $param['uid'];
        }
    
        if($param['headimg']){
            $where['headimg'] = $param['headimg'];
        }
    
        if($param['nickname']){
            $where['nickname'] = $param['nickname'];
        }
    
        if($param['sex']){
            $where['sex'] = $param['sex'];
        }
    
        if($param['signature']){
            $where['signature'] = $param['signature'];
        }
    
        if($param['area']){
            $where['area'] = $param['area'];
        }
    
        if($param['from']){
            $where['from'] = $param['from'];
        }
    
        if($param['desc']){
            $where['desc'] = $param['desc'];
        }
    
        if($param['extend']){
            $where['extend'] = $param['extend'];
        }
        
        if( $param['create_time']!='' ) {
            $create_time = explode('至',$param['create_time']);
            $date_time = [
                strtotime($create_time[0]),
                strtotime($create_time[1].' 23:59:59'),
            ];
            $model->whereBetween('create_time',$date_time);
        }


//        //检索查询
        if($param['search_key']){
            $where['id'] = $param['search_key'];
        }
        if($where){
            $model->where($where);
        }
    }

    //表字段别名
    public static $fieldsList = [
            'id'=>'id',
            'role'=>'role',
            'admin_id'=>'所属公司',
            'depart_id'=>'接待部门',
            'staff_id'=>'接待人',
            'name'=>'客户姓名',
            'mobile'=>'客户手机号',
            'password'=>'password',
            'uid'=>'客户平台id',
            'headimg'=>'headimg',
            'nickname'=>'nickname',
            'sex'=>'sex',
            'signature'=>'signature',
            'area'=>'area',
            'from'=>'from',
            'desc'=>'desc',
            'extend'=>'客户扩展信息',
            'create_time'=>'创建时间',
            'update_time'=>'更新时间',
        'auto_pass'=>'最后活动时间',

    ];

        //表字段状态
        public function getCreateTimeTextAttr($value,$data){
        if(is_numeric($data['create_time'])){
            return $data['create_time']>0 ? date(self::$formatTime,$data['create_time']) : '--';
        }else{
            return $data['create_time'];
        }
    }

    public function getUpdateTimeTextAttr($value,$data){
        if(is_numeric($data['update_time'])){
            return $data['update_time']>0 ? date(self::$formatTime,$data['update_time']) : '--';
        }else{
            return $data['update_time'];
        }
    }



}
